package iziswing.composant;


import iziswing.SwingXml;

import java.awt.Container;
import java.awt.Point;
import java.util.List;

import javax.swing.DefaultListModel;
import javax.swing.JComponent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import metier.ContexteComposant;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import exception.ComposantException;
import exception.DisplayException;
import exception.SwingXmlException;

@SuppressWarnings("serial")
public class JList extends javax.swing.JList implements ListSelectionListener {

	private static Logger mLogger = Logger.getLogger(JTextField.class.getName());

	private Container mFenetre;
	private DefaultListModel mDlm;
	private ContexteComposant mContexte;

	public JList(Container aFenetre, ContexteComposant aContexte) throws ComposantException {
		super();
		mDlm = new DefaultListModel();
		this.setModel(mDlm);
		mFenetre = aFenetre;
		mContexte = aContexte;
		addListSelectionListener(this);
		Point lPoint = ComposantTools.getSize(mContexte);
		setBounds(mContexte.getX(),mContexte.getY(),lPoint.y,lPoint.x);
		refresh();
		mFenetre.add(this);
	}

	public JList() {
		super();
	}

	@SuppressWarnings("unchecked")
	public void refresh() throws ComposantException {
		if (mFenetre != null) {
			Object lObject;
			try {
				lObject = SwingXml.getObjectValue(mFenetre, mContexte.getBean());
				List<Object> lListe = (List<Object>) lObject;
				mDlm.removeAllElements();
				for (Object lObjectTemp : lListe) {
					mDlm.addElement(lObjectTemp);
				}
			} catch (SwingXmlException e) {
				throw new ComposantException(e);
			}
			
		}
	}

	public void clear() {
		mDlm.removeAllElements();
	}
	
	@SuppressWarnings("unchecked")
	public static Object newInstance(Container aFenetre, ContexteComposant aContexte,Object aComposantOut) throws ComposantException{
		try {
			Class<JComponent> lComposant = (Class<JComponent>) Class.forName(aContexte.getModeleClasse().getClasse());
			if(lComposant.equals(JList.class)){
				aComposantOut = new JList(aFenetre,aContexte); 
			}
		} catch (ClassNotFoundException e) {
			mLogger.debug(e);
		}
		return aComposantOut;
	}

	@Override
	public void valueChanged(ListSelectionEvent aE) {
		if (mFenetre != null && StringUtils.isNotBlank(mContexte.getAction())) {
			try {
				SwingXml.action(mFenetre, mContexte.getAction());
			} catch (SwingXmlException e) {
				(new DisplayException(e)).display();
			}
		}
	}

}
